package com.haierp.service.yitao.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Lists;
import com.haierp.enums.OrderStatus;
import com.haierp.enums.PlatformType;
import com.haierp.mapper.*;
import com.haierp.model.Inventory;
import com.haierp.model.ItemSku;
import com.haierp.model.item.OuterItemSku;
import com.haierp.model.sale.OuterOrder;
import com.haierp.model.sale.OuterOrderDetail;
import com.haierp.service.*;
import com.haierp.service.item.IOuterItemService;
import com.haierp.service.yitao.IYtOrderService;
import com.haierp.util.DateUtil;
import com.haierp.util.DimensionCodeUtil;
import com.haierp.util.yitao.YtDimensionCodeUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class IYtOrderServiceImpl implements IYtOrderService {

    protected Logger logger = LogManager.getLogger(getClass());

    @Autowired
    private ISequenceUtilService sequenceUtilService;

    @Autowired
    private OuterOrderMapper outerOrderMapper;

    @Autowired
    private OuterOrderDetailMapper outerOrderDetailMapper;

    @Autowired
    OuterItemMapper outerItemMapper;

    @Autowired
    OuterItemSkuMapper outerItemSkuMapper;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ItemSkuMapper itemSkuMapper;

    @Autowired
    private IInventoryService inventoryService;

    @Autowired
    private IItemSkuService itemSkuService;

    @Autowired
    private IOuterItemService outerItemService;

    @Autowired
    private IItemService itemService;

    @Autowired
    private IOuterOrderService outerOrderService;

    @Override
    public List<Long> yitaoTradesAdd() {
        //交易状态更新的结束时间,值为当前时间
        Date EndUpdate = new Date();
        //交易状态更新的开始时间,值为当前时间的1个小时前，因为定时任务设置为半个小时,这样每个订单会有2次抓取机会
        Date StartUpdate = DateUtil.getDateByCalculate(EndUpdate, Calendar.HOUR_OF_DAY, -1);
        return yitaoTradesAdd(StartUpdate, EndUpdate);
    }

    @Override
    public List<Long> yitaoTradesAdd(Date staDate, Date endDate) {

        logger.info("定时任务：自动去一桃订单===>START");
        List<Long> outOrderIdList = new ArrayList<Long>();
        Map<String, String> params = new HashMap<>();
        String path = "/yitao/api/order/list";
        Integer pageNo = 1;
        Integer pageSize = 1;
        Date date = new Date();
        while (pageSize >= pageNo) {
            Integer page_size = 20;
            params.put("staDate", DimensionCodeUtil.getSecondTimestamp(staDate).toString());
            params.put("endDate", DimensionCodeUtil.getSecondTimestamp(endDate).toString());
            //params.put("status","waiting");
            params.put("pageNo", pageNo.toString());
            params.put("pageSize", page_size.toString());
            pageNo++;
            try {
                String string = YtDimensionCodeUtil.yitaoHttpRequest(path, params, "GET");
                JSONObject jsonObject123 = new JSONObject();
                ObjectMapper mapper = new ObjectMapper();
                Map<String, Object> m = mapper.readValue(string, Map.class);
                Object packageList = m.get("list");
                Object data = jsonObject123.get("page");
                pageSize = (Integer) m.get("size");
                logger.info("一桃待同步订单信息：" + packageList.toString());
                JSONArray fromObject2 = JSONArray.fromObject(packageList);
                if (fromObject2.isEmpty()) {
                    return outOrderIdList;
                }
                for (Object object3 : fromObject2) {
                    JSONObject fromObject3 = JSONObject.fromObject(object3);
                    String orderId = fromObject3.getString("id");
                    String pathDetail = "/yitao/api/order/details";
                    HashMap<String, String> orderDetails = new HashMap<>();
                    orderDetails.put("orderId", orderId);
                    String result = YtDimensionCodeUtil.yitaoHttpRequest(pathDetail, orderDetails, "post");
                    JSONObject fromObject4 = JSONObject.fromObject(result);
                    String tf = fromObject4.getString("status");
                    if (tf.equals("0")) {
                        for (int i = 0; i < 10; i++) {
                            String pathDetailOne = "/yitao/api/order/details";
                            String resultOne = YtDimensionCodeUtil.yitaoHttpRequest(pathDetailOne, orderDetails, "GET");
                            JSONObject fromObject5 = JSONObject.fromObject(resultOne);
                            tf = fromObject5.getString("status");
                            if (tf.equals("0")) {
                                break;
                            }
                        }
                        if (!tf.equals("0")) {
                            logger.error("一桃科技未拉到的订单详情orderId：" + orderId);
                            continue;
                        }
                    }
                    Object object = fromObject4.get("data");
                    JSONObject param = JSONObject.fromObject(object);
                    //如果一桃科技订单已存在，略过
                    OuterOrder p = new OuterOrder();
                    String orderCode = param.getString("orderCode");
                    p.setTargetNo(orderCode);
                    if (outerOrderMapper.selectCount(p) > 0) {
                        logger.info("一桃科技订单已存在：" + orderCode);
                        continue;
                    }
                    //如果一桃科技还不存在，继续
                    OuterOrder outerOrder = new OuterOrder();
                    outerOrder.setCompanyId(1L);//一桃科技如花合作公司
                    outerOrder.setSalesName("一桃平台");
                    outerOrder.setSalesId(48L);
                    outerOrder.setTargetNo(orderCode);//一桃订单编号
                    Long targetId = param.getLong("targetId");
                    String targetCode = param.getString("targetCode");
                    outerOrder.setIdCard(param.getString("buyerCardNo"));//身份证号码
                    outerOrder.setPlatformType(PlatformType.YITAO.getCode());
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String payTimeTemp = param.getString("payTime");//支付时间
                    String createTime = param.getString("createTime");//下单时间 //操作时间
                    // Long confirmTimeTemp = param.getLong("confirm_time") * 1000;
                    //String payTimeTempsd = sdf.format(new Date(payTimeTemp));
                    String timeTempsd = createTime;
                    String confirmTimeTempsd = createTime;
                    Date payTime = null;
                    if (payTimeTemp == null && payTimeTemp != "null") {
                        payTime = sdf.parse(payTimeTemp);
                    }
                    Date time = sdf.parse(timeTempsd);
                    Date confirmTime = sdf.parse(confirmTimeTempsd);
                    outerOrder.setOrderNo("P" + String.format("%0" + 3 + "d", 3) + String.format("%0" + 3 + "d", 4) + "D" + DateUtil.formatDate(time, DateUtil.DATE_PARTEN_YYMMDDHHMMSS) + sequenceUtilService.gainORDSequence());    //系统自动生成
                    outerOrder.setOrderTime(time);                                                     //付款时间
                    outerOrder.setStatus(OrderStatus.INIT.getCode());                                     //状态：新建
                    outerOrder.setReceiver(param.getString("nickName"));                             //收货人
                    outerOrder.setReceiverState(param.getString("province"));
                    outerOrder.setReceiverCity(param.getString("city"));                                 //市
                    outerOrder.setReceiverDistrict(param.getString("area"));                         //区
                    outerOrder.setAddressDetail(param.getString("address"));                     //详细地址
                    outerOrder.setTelephone(param.getString("phone"));                             //联系电话
                    outerOrder.setPostcode(null);                                                         //邮编
                    outerOrder.setRemark(null);
                    //买家购买附言
                    outerOrder.setPayment(param.getDouble("actualAmountYuan"));//实付金额
                    //outerOrder.setIdCard(null);                                                          //身份证
                    outerOrder.setUserCreate("一桃定时任务");                                                 //创建者
                    outerOrder.setGmtCreate(date);                                                         //创建时间
                    outerOrder.setGmtModify(date); 
                    if (targetId.equals("null") && targetCode.equals("null")) {
                        outerOrder.setId(targetId);
                        outerOrder.setOrderNo(targetCode);
                        System.out.print("[修改订单]订单参数 ： targetId  =" + targetId + "targetCode = " + targetCode);
                        outerOrderMapper.updateById(outerOrder);
                    } else {
                        System.out.print("[添加主订单信息]");
                        outerOrderMapper.insert(outerOrder);   
                        outOrderIdList.add(outerOrder.getId());       //收集主订单ID
                    }
                    List<OuterOrderDetail> outerOrderDetails = new ArrayList<OuterOrderDetail>();
                    Object itemList = param.get("cmsMallOrderDetailVoList");
                    JSONArray itemdetailList = JSONArray.fromObject(itemList);
                    for (Object itemdetailTemp : itemdetailList) {
                        JSONObject itemdetail = JSONObject.fromObject(itemdetailTemp);
                        OuterOrderDetail outerOrderDetail = new OuterOrderDetail();
                        outerOrderDetail.setOuterOrderId(outerOrder.getId());                             //主订单ID
                        outerOrderDetail.setCompanyId(outerOrder.getCompanyId());                        // 订单所属公司
                        outerOrderDetail.setItemId(itemdetail.getLong("outId"));//如花产品ID
                        Long productSkuId = itemdetail.getLong("sourceSkuId");
                        outerOrderDetail.setThirdSkuCode(itemdetail.getString("productSkuId"));//一桃skuId
                        ItemSku tjItemSku = null;
                        if (productSkuId != null) {
                            /*OuterItemSku ois = new OuterItemSku();
                            ois.setSkuId(productSkuId);
                            OuterItemSku outerItemSku = outerItemSkuMapper.selectOne(ois);*/
                        	ItemSku itemSku = itemSkuService.selectById(productSkuId);
                            if (itemSku != null) {
                                outerOrderDetail.setSkuCode(itemSku.getSkuCode());                         //sku编码
                                outerOrderDetail.setSkuId(itemSku.getId());
                                outerOrderDetail.setColor(itemSku.getColor());
                                outerOrderDetail.setScale(itemSku.getScale());
                                outerOrderDetail.setSkuPic(itemSku.getSkuPic());
                                tjItemSku = new ItemSku();
                                tjItemSku.setSkuCode(itemSku.getSkuCode());
                            }
                        }
                        outerOrderDetail.setSalePrice(itemdetail.getDouble("productSalesPriceYuan"));                 //商品单价
                        outerOrderDetail.setQuantity(itemdetail.getInt("quantity"));                             //购买数量
                        outerOrderDetail.setOid(null);                                                   //商品交易明细编号
                        outerOrderDetail.setItemName(itemdetail.getString("productName"));
                        outerOrderDetail.setItemId(itemdetail.getLong("outId"));
                       
                        outerOrderDetail.setGmtCreate(date);                                             //创建时间
                        outerOrderDetail.setGmtModify(date);                                         //修改时间
                        outerOrderDetails.add(outerOrderDetail);
                        //如果有虚拟库存就扣减虚拟库存
                        if (tjItemSku != null) {
                            ItemSku itemSku = itemSkuService.selectOne(tjItemSku);
                            if (itemSku != null) {
                                Inventory inventory = inventoryService.queryInventoryBySkuId(itemSku.getItemId(), itemSku.getId());
                                if (inventory.getVirtualInv() > 0) {
                                    int virtualInv = inventory.getVirtualInv() - outerOrderDetail.getQuantity();
                                    virtualInv = virtualInv > 0 ? virtualInv : 0;
                                    //如果虚拟库存小于等于可售库存，虚拟库存清零
                                    virtualInv = virtualInv > inventory.getTotalAvailableInv() ? virtualInv : 0;
                                    //如果虚拟占用库存大于零，有赞下单不应该减少虚拟预扣
                                    if (inventory.getLockedVirtualInv() > 0) {
                                        int lockedVirtualInv = inventory.getLockedVirtualInv() - outerOrderDetail.getQuantity();
                                        lockedVirtualInv = lockedVirtualInv > 0 ? lockedVirtualInv : 0;
                                        inventory.setLockedVirtualInv(lockedVirtualInv);
                                    }
                                    inventory.setCompanyId(itemSku.getCompanyId());                          //所属
                                    inventory.setVirtualInv(virtualInv);
                                    inventory.setGmtModify(new Date());
                                    inventoryService.updateSelectiveById(inventory);
                                }
                            }
                        }
                    }
                    if (targetId != null && targetCode != null) {
                    	 logger.info("一桃订单明细已存在：" + orderCode);
                         continue;
                    } else {
                    	 outerOrderDetailMapper.insertBatch(outerOrderDetails);                                            //添加主订单
                    }
                                           
                }
            } catch (Exception e) {
                logger.error(e);
            }
        }
        if (outOrderIdList.size() > 0) {
            //把商品详情更新到主订单明细里面
            outerOrderDetailMapper.updateOuterOrderDetailByItemSku(outOrderIdList);
        }
        return outOrderIdList;
    }

    @Override
    public List<Long> yitaoPushOrder(HttpServletRequest request) {
        logger.info("一桃订单消息推送===> START");
        List<Long> outOrderIdList = new ArrayList<Long>();
        Date date = new Date();
        // logger.error("推送消息：" + entity.toString());
        InputStream in;
        try {
            in = request.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            String jsonStr = br.readLine();
            logger.info("一桃订单消息推送===> " + jsonStr);
            JSONObject fromObject4 = JSONObject.fromObject(jsonStr);
            Object object = fromObject4.get("data");
            JSONObject param = JSONObject.fromObject(object);
            //如果一桃科技订单已存在，略过
            OuterOrder p = new OuterOrder();
            String orderCode = param.getString("orderCode");
            p.setTargetNo(orderCode);
            if (outerOrderMapper.selectCount(p) > 0) {
                logger.info("一桃科技订单===> " + orderCode);
                return Lists.newArrayList();
            }
            //如果一桃科技还不存在，继续
            OuterOrder outerOrder = new OuterOrder();
            outerOrder.setCompanyId(1L);//一桃科技如花合作公司
            outerOrder.setSalesName("一桃平台");
            outerOrder.setSalesId(48L);
            outerOrder.setIdCard(param.getString("buyerCardNo"));//身份证号码
            outerOrder.setTargetNo(orderCode);//一桃订单编号
            String targetId =  param.getString("targetId");
            String targetCode = param.getString("targetCode");
            outerOrder.setPlatformType(PlatformType.YITAO.getCode());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String payTimeTemp = param.getString("payTime");//支付时间
            String createTime = param.getString("createTime");//下单时间 //操作时间
            // Long confirmTimeTemp = param.getLong("confirm_time") * 1000;
            //String payTimeTempsd = sdf.format(new Date(payTimeTemp));
            String timeTempsd = createTime;
            String confirmTimeTempsd = createTime;
            Date payTime = null;
            if (payTimeTemp == null && payTimeTemp != "null") {
                payTime = sdf.parse(payTimeTemp);
            }
            Date time = sdf.parse(timeTempsd);
            Date confirmTime = sdf.parse(confirmTimeTempsd);
            outerOrder.setOrderNo("P" + String.format("%0" + 3 + "d", 3) + String.format("%0" + 3 + "d", 4) + "D" + DateUtil.formatDate(time, DateUtil.DATE_PARTEN_YYMMDDHHMMSS)/* + sequenceUtilService.gainORDSequence()*/);    //系统自动生成
            outerOrder.setOrderTime(time);                                                     //付款时间
            outerOrder.setStatus(OrderStatus.INIT.getCode());                                     //状态：新建
            outerOrder.setReceiver(param.getString("nickName"));                             //收货人
            outerOrder.setReceiverState(param.getString("province"));
            outerOrder.setReceiverCity(param.getString("city"));                                 //市
            outerOrder.setReceiverDistrict(param.getString("area"));                         //区
            outerOrder.setAddressDetail(param.getString("address"));                     //详细地址
            outerOrder.setTelephone(param.getString("phone"));                             //联系电话
            outerOrder.setPostcode(null);                                                         //邮编
            outerOrder.setRemark(null);
            //买家购买附言
            outerOrder.setPayment(param.getDouble("actualAmountYuan"));//实付金额
            //outerOrder.setIdCard(null);                                                          //身份证
            outerOrder.setUserCreate("一桃推送");                                                 //创建者
            outerOrder.setGmtCreate(date);                                                         //创建时间
            outerOrder.setGmtModify(date);                                                 //修改时间
            logger.info("一桃科技订单待添加订单参数===> " + outerOrder.toString());
            if (!targetId.equals("null") || !targetCode.equals("null")) {
                outerOrder.setId( Long.valueOf(targetId).longValue());
                outerOrder.setOrderNo(targetCode);
                System.out.print("[修改订单]订单参数 ： targetId  =" + targetId + "targetCode = " + targetCode);
                outerOrderMapper.updateById(outerOrder);
            } else {
                System.out.print("[添加主订单信息]");
                outerOrderMapper.insert(outerOrder);   
                outOrderIdList.add(outerOrder.getId()); // 收集主订单ID
            }
            List<OuterOrderDetail> outerOrderDetails = new ArrayList<OuterOrderDetail>();
            Object itemList = param.get("cmsMallOrderDetailVoList");
            JSONArray itemdetailList = JSONArray.fromObject(itemList);
            for (Object itemdetailTemp : itemdetailList) {
                JSONObject itemdetail = JSONObject.fromObject(itemdetailTemp);
                OuterOrderDetail outerOrderDetail = new OuterOrderDetail();
                outerOrderDetail.setOuterOrderId(outerOrder.getId());                             //主订单ID
                outerOrderDetail.setCompanyId(outerOrder.getCompanyId());                        // 订单所属公司
                outerOrderDetail.setOuterOrderId(outerOrder.getId());
                outerOrderDetail.setThirdSkuCode(itemdetail.getString("productSkuId"));//一桃skuId
                Long productSkuId = itemdetail.getLong("sourceSkuId");
                ItemSku tjItemSku = null;
                if (productSkuId != null) {
                	 ItemSku itemSku = itemSkuService.selectById(productSkuId);
                   /*OuterItemSku ois = new OuterItemSku();
                    ois.setSkuId(productSkuId);
                    OuterItemSku outerItemSku = outerItemSkuMapper.selectOne(ois);*/
                  if (itemSku != null) {
                        tjItemSku = new ItemSku();
                        outerOrderDetail.setSkuCode(itemSku.getSkuCode());                         //sku编码
                        outerOrderDetail.setSkuId(itemSku.getId());
                        tjItemSku.setSkuCode(itemSku.getSkuCode());
                    }
                }
                outerOrderDetail.setSalePrice(itemdetail.getDouble("productSalesPriceYuan"));                 //商品单价
                outerOrderDetail.setQuantity(itemdetail.getInt("quantity"));                             //购买数量
                outerOrderDetail.setOid(null);                                                   //商品交易明细编号
                outerOrderDetail.setItemName(itemdetail.getString("productName"));
                outerOrderDetail.setItemId(itemdetail.getLong("outId"));
                outerOrderDetail.setGmtCreate(date);                                             //创建时间
                outerOrderDetail.setGmtModify(date);                                         //修改时间
                outerOrderDetails.add(outerOrderDetail);
                //如果有虚拟库存就扣减虚拟库存
                if (tjItemSku != null) {
                    ItemSku itemSku = itemSkuService.selectOne(tjItemSku);
                    if (itemSku != null) {
                        Inventory inventory = inventoryService.queryInventoryBySkuId(itemSku.getItemId(), itemSku.getId());
                        if (inventory.getVirtualInv() > 0) {
                            int virtualInv = inventory.getVirtualInv() - outerOrderDetail.getQuantity();
                            virtualInv = virtualInv > 0 ? virtualInv : 0;
                            //如果虚拟库存小于等于可售库存，虚拟库存清零
                            virtualInv = virtualInv > inventory.getTotalAvailableInv() ? virtualInv : 0;
                            //如果虚拟占用库存大于零，有赞下单不应该减少虚拟预扣
                            if (inventory.getLockedVirtualInv() > 0) {
                                int lockedVirtualInv = inventory.getLockedVirtualInv() - outerOrderDetail.getQuantity();
                                lockedVirtualInv = lockedVirtualInv > 0 ? lockedVirtualInv : 0;
                                inventory.setLockedVirtualInv(lockedVirtualInv);
                            }
                            inventory.setCompanyId(itemSku.getCompanyId());                          //所属
                            inventory.setVirtualInv(virtualInv);
                            inventory.setGmtModify(new Date());
                            inventoryService.updateSelectiveById(inventory);
                        }
                    }
                }
            }
            logger.info("一桃科技订单待添加商品参数===> " + outerOrderDetails.toString());
            if (targetId.equals("null") || targetCode.equals("null")) {
            	outerOrderDetailMapper.insertBatch(outerOrderDetails);            
           }
            /*if (outOrderIdList.size() > 0) {
                //生成子订单并配货
                outOrderIdList.forEach(erpOrderId -> {
                    outerOrderService.review(erpOrderId, "YT");
                });
            }//添加子订单*/
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        logger.info("一桃科技订单推送===> END ");
        return outOrderIdList;
    }

    @Override
    public Map yitaoPullOrder(HttpServletRequest request) {
        logger.info("一桃订单消息拉取订单===> START");
        Map res = new HashMap();
        res.put("code", 0);
        res.put("msg", "success");
        InputStream in;
        try {
            in = request.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            String jsonStr = br.readLine();
            logger.info("一桃订单消息拉取订单===> " + jsonStr);
            JSONObject fromObject4 = JSONObject.fromObject(jsonStr);
            Object object = fromObject4.get("data");
            //JSONObject param = JSONObject.fromObject(object);
            //JSONArray orderIdList = param.getJSONArray("orderIdList");
            List orderIdList = (List) object;
            if (orderIdList == null) {
                res.put("code", 500);
                res.put("msg", "参数异常");
                return res;
            }
            List<String> orderIdListString = orderIdList;
            if (orderIdListString == null) {
                res.put("code", 500);
                res.put("msg", "参数异常");
                return res;
            }
            List<OuterOrder> outerOrders = outerOrderMapper.selectBatchIds(orderIdListString);
            if (outerOrders == null || outerOrders.size() < 1) {
                res.put("code", 500);
                res.put("msg", "无订单信息");
                return res;
            }
            res.put("orderIdList", outerOrders);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        logger.info("一桃科技订单拉取订单===> END ", res);

        return res;
    }

    @Override
    public Map pushOrderDetails(HttpServletRequest request) {
        logger.info("一桃订单详情消息拉取订单===> START");
        Map res = new HashMap();
        res.put("code", 0);
        res.put("msg", "success");
        InputStream in;
        try {
            in = request.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            String jsonStr = br.readLine();
            logger.info("一桃订单详情消息拉取订单===> " + jsonStr);
            JSONObject fromObject4 = JSONObject.fromObject(jsonStr);
            Object object = fromObject4.get("data");
            //JSONObject param = JSONObject.fromObject(object);
            // JSONArray orderIdList = param.getJSONArray("orderIdList");
            Long outerOrderId = Long.valueOf(object.toString());
            if (outerOrderId == null) {
                res.put("code", 500);
                res.put("msg", "参数异常");
                return res;
            }
            if (outerOrderId == null) {
                res.put("code", 500);
                res.put("msg", "参数异常");
                return res;
            }
            List<OuterOrderDetail> outerOrderDetails = outerOrderDetailMapper.selectOuterOrderDetailByOuterOrderId(outerOrderId);
            if (outerOrderDetails == null || outerOrderDetails.size() < 1) {
                res.put("code", 500);
                res.put("msg", "无订单信息");
                return res;
            }
            for (OuterOrderDetail outerOrderDetail :
                    outerOrderDetails) {
                outerOrderDetail.setSkuPic("");
            }
            res.put("outerOrderDetailList", outerOrderDetails);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        logger.info("一桃科技订单详情拉取订单===> END ", res);

        return res;
    }
}
